package com.lightjet.macross.base.auth.config;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;

public class MD5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return getMd5(rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return getMd5(rawPassword.toString()).equals(encodedPassword);
    }

    private String getMd5(String mm){
        String test = null;
        try {
            test = DigestUtils.md5DigestAsHex(mm.getBytes("UTF-16le"));
        } catch (UnsupportedEncodingException e) {
            test = "";
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer(test);
        int l = sb.length()%2 ==0? (sb.length()/2-1):(sb.length()/2);
        for(int i =l; i>0 ;i--)
        {
            sb.insert(i*2,"-");
        }
        //System.out.println(sb.toString().toUpperCase());
        return sb.toString().toUpperCase();
    }
}
